package com.ohuang.util_h.activityInterceptor;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 请配合ActivityInterceptor使用
 * 权限申请前弹对话框
 */
public class PermissionInterceptor implements ActivityInterceptor.IntentInterceptor{

    public PermissionInterceptor() {
    }
    WeakReference<Activity> resumeActivity;
    public void setResumeActivity(Activity context){
        resumeActivity=new WeakReference<>(context);
    }

    @Override
    public boolean isInterceptor(Object proxy, Method method, Object[] args, Intent intent) {

        if (intent!=null) {

            if ("android.content.pm.action.REQUEST_PERMISSIONS".equals(intent.getAction()) && resumeActivity != null&&resumeActivity.get()!=null) {
                AlertDialog dialog = new AlertDialog.Builder(resumeActivity.get())
                        .setTitle("注意")//设置对话框的标题
                        .setMessage("此应用需获得使用此应用的权限")//设置对话框的内容
                        //设置对话框的按钮
                        .setCancelable(false)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    method.invoke(proxy, args);
                                } catch (IllegalAccessException |
                                         InvocationTargetException ignored) {
                                }
                                dialog.dismiss();
                            }
                        }).create();
                dialog.show();

                return true;
            }
        }
        return false;
    }
}
